import { connect, history } from 'umi';
import { SchemaManage } from '@/components/SchemaComponent';
import { useMemo, useRef, useState } from 'react';
import { getTableColumns } from '../mconfig';
import { pullBlackSupplierInfoService, supplierManageService } from '../services';
import { ManageCommonAPI } from '@/pages/type';
import { PlusOutlined, CloudUploadOutlined } from '@ant-design/icons';
import { getKeyRouter } from '@/utils';
import { CancelModal } from '@/components/CancelModal';
import { ILoadMapTypeAll } from '@/common';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { message } from 'antd';
import { BatchImportModal } from '@/components/BatchImportModal';

// import MockManage from '../common/MockManage.json'; //模拟数据-王志龙

const SupplierManageView: React.FC<SupplierManageAPI.IManageType> = ({ curRes, locationProps }) => {
  const schemaManageRef: any = useRef();

  /**  获取管理页数据 */
  const { data, loading, pagination, searchList, getSupplierData, reloadRefresh } = supplierManageService(curRes);

  /**  点击按钮保存数据和弹框控制 */
  const [clickRowObj, setClickRowObj] = useState<Record<string, any>>({
    checkRowObj: {},
    showCancelModal: false,
  });

  /** 点击拉黑供应商 */
  const [clickRowBlackObj, setClickRowBlackObj] = useState<Record<string, any>>({
    blackModal: false,
    checkRowsInfo: {},
  });

  /** 是否显示导入文件弹窗 */
  const [batchImport, setBatchImport] = useState<boolean>(false);

  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    getSupplierData({ ...values }); //模拟数据-王志龙
  };

  /**  搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    getSupplierData({ ...request }); //模拟数据-王志龙
  };

  /** 分页change 方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getSupplierData({ pageSize, current, ...params }); //模拟数据-王志龙
  };

  /**
   * 拉黑接口回调
   * @param res 接口返回
   */
  const pullBlackCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入拉黑接口 */
  const { pullBlackSupplierInfoLoading, pullBlackSupplierInfoRun } = pullBlackSupplierInfoService(pullBlackCallback);

  /** 表格操作按钮点击方法 */
  const onOptClick: SupplierManageAPI.IOperationClick = {
    onView: (resObj) => {
      history.push({
        pathname: `/supplierInfoController/getSupplierById/{id}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: resObj?.id,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onEdit: (resObj) => {
      history.push({
        pathname: `/supplierInfoController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: resObj?.id,
          returnPathName: locationProps?.pathname,
        },
      });
    },
    onCancel: (resObj) => {
      setClickRowObj({
        checkRowObj: resObj,
        showCancelModal: true,
      });
    },
    onPullBlack: (resObj) => {
      setClickRowBlackObj({
        blackModal: true,
        checkRowsInfo: resObj,
      });
    },
  };

  /** 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, onOptClick);
  }, [curRes]);

  /**
   * 操作按钮列表
   */
  const actionList: ManageCommonAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/supplierInfoController/add'] || false,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          history.push({
            pathname: `/supplierInfoController/add/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              returnPathName: locationProps?.pathname,
            },
          });
        },
      },
      {
        title: '导入',
        visible: curRes?.['/supplierInfoController/import'] && curRes?.['/supplierInfoController/batchImportSupplier'] ? true : false,
        type: 'primary',
        icon: <CloudUploadOutlined />,
        onClick: () => {
          setBatchImport(true);
        },
      },
    ];
  }, [curRes]);

  /** 刷新管理页面 */
  const reloadManage = () => {
    reloadRefresh(); //模拟数据-王志龙
  };

  return (
    <>
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList: [],
          searchList,
          onSwitch: () => {},
          onReset,
          onSearch,
        }}
        actionList={actionList}
        tableProps={{
          columns,
          dataSource: data?.rows,
          // dataSource: MockManage, //模拟数据-王志龙
          loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange, //分页onchange
        }}
      />

      {/* 作废弹窗 */}
      {clickRowObj?.showCancelModal && (
        <CancelModal
          modalTitle="作废供应商"
          modalWidth={0.25}
          cancelTypeDic={ILoadMapTypeAll.CANCELTYPE_SUPPLIER}
          checkRows={clickRowObj?.checkRowObj}
          reloadManage={reloadManage}
          onClose={() => {
            setClickRowObj({
              checkRowObj: {},
              showCancelModal: false,
            });
          }}
          cancelRequestUrl={'/supplierInfoController/cancel'}
        />
      )}

      {/* 拉黑供应商 */}
      {clickRowBlackObj?.blackModal && (
        <TipsErrorModalNew
          modalLoading={pullBlackSupplierInfoLoading}
          onClose={() => {
            setClickRowBlackObj({
              blackModal: false,
              checkRowsInfo: {},
            });
          }}
          modalOnOK={() => {
            pullBlackSupplierInfoRun({
              id: clickRowBlackObj?.checkRowsInfo?.id,
              versionNum: clickRowBlackObj?.checkRowsInfo?.versionNum,
            });
          }}
          modalTip={'拉黑后，供应商信息将不可被修改和使用，请确认？'}
        />
      )}

      {/* 导入文件弹窗 */}
      {batchImport && (
        <BatchImportModal
          curRes={curRes}
          modalTitle={'批量导入供应商'}
          onClose={() => setBatchImport(false)}
          templateUrl={'/supplierInfoController/downloadFile'}
          parserImportUrl={'/supplierInfoController/import'}
          batchImportUrl={'/supplierInfoController/batchImportSupplier'}
          refreshCallback={() => reloadRefresh()}
          filePath={'/minfile/purchase/template/供应商信息导入模板.xlsx'}
        />
      )}
    </>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(SupplierManageView);
